package cn.bluethink.eguan.okrtask.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.bluethink.eguan.core.security.Token;
import cn.bluethink.eguan.core.service.EgUserService;
import cn.bluethink.eguan.filter.NameFilter;
import cn.bluethink.eguan.model.core.EgPurview;
import cn.bluethink.eguan.model.core.EgRole;
import cn.bluethink.eguan.model.core.EgTaskStatus;
import cn.bluethink.eguan.model.core.EgUser;
import cn.bluethink.eguan.model.okrtask.EgOkrTask;
import cn.bluethink.eguan.model.okrtask.EgTaskKR;
import cn.bluethink.eguan.okrtask.service.EgOKRTaskService;
import cn.bluethink.eguan.okrtask.service.EgTaskKRService;
import cn.bluethink.eguan.result.PageInfo;
import cn.bluethink.eguan.result.ResponseMessage;
import cn.bluethink.eguan.result.ResponseResult;

/**
 * 工作任务关键项控制器
 * 
 * @title 苏州中科蓝迪公司所有(c)2016-2021
 * @version 0.1.0
 * @describe 
 * @author liuxn
 * @date  2018年10月19日
 * 		  （1） liuxn于2018年10月19日创建初版本
 * 		 （2） liuxn于2018年11月6日关键项添加备注
 * 		  （3） liuxn于2018年11月7日修订关键项创建、修改和删除逻辑，拥有任务管理权限的用户均可创建、修改和删除关键项
 * 		  （4） liuxn于2018年11月13日调整评分评价逻辑，放开限制
 * 		 (5) liuxn于2018年12月17日添加关键项指派人和截止日期
 */
@CrossOrigin
@RestController
@RequestMapping("/eguan/v1.0/taskkr")
public class EgTaskKRController {
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private EgTaskKRService krService;
	
	@Autowired
	private EgOKRTaskService okrService;
	
	@Autowired
	private EgUserService userService;

	/**
	 * 添加关键项
	 * @param tid
	 * @param content
	 * @return
	 * @throws Exception
	 */
	@Token
	@PostMapping("/create")
	public ResponseResult<EgTaskKR> create(@RequestParam Long tid, @RequestParam String krContent) throws Exception {
		// 1、获取当前登录用户Id
		//String token = request.getHeader("Authorization");
		Long uid = (Long)request.getAttribute("userId");
		// 2、关键项内容不能为空
		if(krContent == null || "".equals(krContent)) return new ResponseResult<>(ResponseMessage.NOTNULL_CONTENT);
		// 3、根据任务Id获取当前任务基本信息
		EgOkrTask task = okrService.getById(tid);
		// 4、如果任务为空，返回查询失败
		if(task == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        // 5、获取当前登录用户在该任务中的权限
        EgUser user = userService.getUser(uid, false);
        EgRole role = okrService.roleintask(task, user);
		// 6、否则，判断当前登录用户是否为该任务发布者
//		if(!task.getCuser().getId().equals(uid)) return new ResponseResult<>(ResponseMessage.INADEQUATE_PERMISSIONS);
        if((role.getPurview() & EgPurview.OKR_TASK_MG) != EgPurview.OKR_TASK_MG) 
        	return new ResponseResult<>(ResponseMessage.INADEQUATE_PERMISSIONS);
		// 7、创建任务关键项
		EgTaskKR taskkr = krService.create(task, krContent,uid);
		if(taskkr == null) return new ResponseResult<>(ResponseMessage.CREATE_FAIL);
		return new ResponseResult<>(ResponseMessage.OK, taskkr);
	}
	
	/**
	 * 修改关键项（基本信息、状态）
	 * @param taskKR
	 * @return
	 * @throws Exception
	 */
	@Token
	@PostMapping("/update")
	public ResponseResult<EgTaskKR> update(@RequestBody EgTaskKR taskKR) throws Exception {
		// 1、获取当前登录用户Id
		//String token = request.getHeader("Authorization");
		Long uid = (Long)request.getAttribute("userId");
		// 2、判断关键结果ID是否为空，为空，返回参数错误
		if(taskKR.getId() == null || taskKR.getId() == 0) return new ResponseResult<>(ResponseMessage.NOTNULL_ID);
		// 3、根据关键项Id查询关键项信息
		EgTaskKR krdetail = krService.detail(taskKR.getId());
		// 4、如果关键项为空，返回查询失败
		if(krdetail == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND); 
		// 5、根据任务Id获取当前任务基本信息
		EgOkrTask task = okrService.getById(krdetail.getTid());
		// 6、如果任务为空，返回查询失败
		if(task == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        // 获取当前登录用户在该任务中的权限
        EgUser user = userService.getUser(uid, false);
        EgRole role = okrService.roleintask(task, user);
		// 7、否则，判断状态是否未改变，状态未改变并且拥有任务管理权限，更新关键结果基本信息
		EgTaskKR result = null;
		if(( task.getCuser().equals(user) || (role.getPurview() & EgPurview.OKR_TASK_MG) == EgPurview.OKR_TASK_MG ) && taskKR.bnullStatus(krdetail.getStatus()))  {
			if(krdetail.beenGraded()) return new ResponseResult<>(ResponseMessage.UPDATE_FAIL.getStatus(), "已被评分，不能修改基本信息！");
			result = krService.update(task, krdetail, taskKR, uid);
		}
		// 8、判断当前登录用户是否为任务被指派人，如果为被指派人，更新关键结果状态
		else if(task.getDouser() != null && (task.getDouser().getId().equals(uid) || krdetail.getDouser().getId().equals(uid)) && !taskKR.bnullStatus(krdetail.getStatus())) {
        	// 10、如果关键项已被评分，不允许修改状态
			if(krdetail.beenGraded()) return new ResponseResult<>(ResponseMessage.UPDATE_FAIL.getStatus(), "已被评分，不能修改状态！");
			result = krService.updateStatus(task, krdetail, taskKR, uid);
		} else {
			return new ResponseResult<>(ResponseMessage.INADEQUATE_PERMISSIONS);
		}
		if(result == null) return new ResponseResult<>(ResponseMessage.UPDATE_FAIL);
		return new ResponseResult<>(ResponseMessage.OK, result);
	}

	/**
	 * 对关键项进行评分
	 * @param taskKR
	 * @return
	 * @throws Exception
	 */
	@Token
	@PostMapping("/evaluate")
	public ResponseResult<EgTaskKR> evaluate(@RequestBody EgTaskKR taskKR) throws Exception {
		// 1、获取当前登录用户Id
		//String token = request.getHeader("Authorization");
	    Long uid = (Long)request.getAttribute("userId");
		// 2、判断关键结果ID是否为空，为空，返回参数错误
		if(taskKR.getId() == null || taskKR.getId() == 0) return new ResponseResult<>(ResponseMessage.NOTNULL_ID);
		// 3、根据关键项Id查询关键项信息
		EgTaskKR krdetail = krService.detail(taskKR.getId());
		// 4、如果关键项为空，返回查询失败
		if(krdetail == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND); 
		// 5、关键项未完成，不允许评分
		if((krdetail.getStatus() & EgTaskStatus.STATUS_FINISH) != EgTaskStatus.STATUS_FINISH) 
			return new ResponseResult<>(ResponseMessage.UPDATE_FAIL.getStatus(), "关键项未完成，不能评分！");
		// 6、根据任务Id获取当前任务基本信息
		EgOkrTask task = okrService.getById(krdetail.getTid());
		// 7、如果任务为空，返回查询失败
		if(task == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        // 获取当前登录用户在该任务中的权限
        EgUser user = userService.getUser(uid, false);
        EgRole role = okrService.roleintask(task, user);
        if((role.getPurview() & EgPurview.OKR_TASK_MG) == EgPurview.OKR_TASK_MG) {
    		// 调整逻辑，放开评分评价限制条件
        	taskKR.setDouser(krdetail.getDouser());
        	taskKR.setEtime(krdetail.getEtime());
        	taskKR.setFtime(krdetail.getFtime());
    		taskKR.setRemark(krdetail.getRemark());
    		EgTaskKR result = krService.evaluateScore(task, krdetail,taskKR,uid);
    		if(result == null) return new ResponseResult<>(ResponseMessage.UPDATE_FAIL.getStatus(), "评分失败！");
    		return new ResponseResult<>(ResponseMessage.OK, result);
        }
        return new ResponseResult<>(ResponseMessage.INADEQUATE_PERMISSIONS);
	}

	/**
	 * 备注关键项完成情况
	 * @param taskKR
	 * @return
	 * @throws Exception
	 */
	@Token
	@PostMapping("/remark")
	public ResponseResult<EgTaskKR> remark(@RequestParam Long krid, @RequestParam String remark) throws Exception {
		// 1、获取当前登录用户Id
		//String token = request.getHeader("Authorization");
		Long uid = (Long)request.getAttribute("userId");
		// 2、判断关键结果ID是否为空，为空，返回参数错误
		if(krid == null || krid == 0) return new ResponseResult<>(ResponseMessage.NOTNULL_ID);
		// 3、根据关键项Id查询关键项信息
		EgTaskKR krdetail = krService.detail(krid);
		// 4、如果关键项为空，返回查询失败
		if(krdetail == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND); 
		// 如果备注不为空，且和已有数据不相等，不需要更新操作
		if(krdetail.getRemark() != null && remark != null && remark.trim().equals(krdetail.getRemark().trim())) {
			return new ResponseResult<>(ResponseMessage.OK);
		}
		// 6、根据任务Id获取当前任务基本信息
		EgOkrTask task = okrService.getById(krdetail.getTid());
		// 7、如果任务为空，返回查询失败
		if(task == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
		if(task.getDouser() != null &&  (task.getDouser().getId().equals(uid) || krdetail.getDouser().getId().equals(uid)))  {
			krdetail.setRemark(remark);
			EgTaskKR result = krService.updateRemark(task, krdetail, uid);
			if(result == null) return new ResponseResult<>(ResponseMessage.UPDATE_FAIL.getStatus(), "备注失败！");
			return new ResponseResult<>(ResponseMessage.OK, result);
		}
		return new ResponseResult<>(ResponseMessage.INADEQUATE_PERMISSIONS);
	}
	
	/**
	 * 删除关键项
	 * @param krid
	 * @return
	 * @throws Exception
	 */
	@Token(purviews = {EgPurview.OKR_TASK_MG, EgPurview.OBJECT_CHECK})
	@PostMapping("/del")
	public ResponseResult<Long> del(@RequestParam Long krid) throws Exception {
		// 1、获取当前登录用户Id
		//String token = request.getHeader("Authorization");
		Long uid = (Long)request.getAttribute("userId");
		// 2、判断关键结果ID是否为空，为空，返回参数错误
		if(krid == null || krid == 0) return new ResponseResult<>(ResponseMessage.NOTNULL_ID);
		// 3、根据关键项Id查询关键项信息
		EgTaskKR krdetail = krService.detail(krid);
		// 4、如果关键项为空，返回查询失败
		if(krdetail == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND); 
		// 5、根据任务Id获取当前任务基本信息
		EgOkrTask task = okrService.getById(krdetail.getTid());
		// 6、如果任务为空，返回查询失败
		if(task == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        // 7、获取用户的详情
        EgUser user = userService.getUser(uid, false);
        // 获取当前登录用户在该任务中的权限
        EgRole role = okrService.roleintask(task, user);
        // 8、如果用户拥有审核权限，可直接删除
        if((role.getPurview() & EgPurview.OBJECT_CHECK) == EgPurview.OBJECT_CHECK) {
            if(krService.del(task,uid,krdetail) == null) return new ResponseResult<>(ResponseMessage.DELETE_FAIL);
            return new ResponseResult<>(ResponseMessage.OK, krid);
        }
		// 9、如果用户拥有任务管理的权限，可以删除
        if((role.getPurview() & EgPurview.OKR_TASK_MG) == EgPurview.OKR_TASK_MG) {
        	// 10、如果关键项已被评分，不允许删除
    		if(krdetail.beenGraded()) return new ResponseResult<>(ResponseMessage.UPDATE_FAIL.getStatus(), "已被评分，不能删除！");
            if(krService.del(task,uid,krdetail) == null) return new ResponseResult<>(ResponseMessage.DELETE_FAIL);
            return new ResponseResult<>(ResponseMessage.OK, krid);
        }
        return new ResponseResult<>(ResponseMessage.INADEQUATE_PERMISSIONS);
	}

	/**
	 * 根据过滤条件查询关键项列表
	 * 此处只根据任务Id查询
	 * @param filter
	 * @return
	 * @throws Exception
	 */
	@Token
	@PostMapping("/query")
	public ResponseResult<PageInfo<EgTaskKR>> query(@RequestBody NameFilter filter) throws Exception {
		return new ResponseResult<>(ResponseMessage.OK, krService.query(filter));
	}

	/**
	 * 关键结果拖拽排序
	 * @param krid
	 * @param sort
	 * @return
	 * @throws Exception
	 */
    @Token
    @PostMapping("/sort")
    public ResponseResult<Long> sort(@RequestParam Long krid, @RequestParam Integer sort) throws Exception {
    	// 1、获取当前登录用户Id
		//String token = request.getHeader("Authorization");
		Long uid = (Long)request.getAttribute("userId");
		// 2、判断关键结果ID是否为空，为空，返回参数错误
		if(krid == null || krid == 0) return new ResponseResult<>(ResponseMessage.NOTNULL_ID);
		// 3、根据关键项Id查询关键项信息
		EgTaskKR krdetail = krService.detail(krid);
		// 4、如果关键项为空，返回查询失败
		if(krdetail == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND); 
		// 5、根据任务Id获取当前任务基本信息
		EgOkrTask task = okrService.getById(krdetail.getTid());
		// 6、如果任务为空，返回查询失败
		if(task == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
	    // 7、获取用户的详情
	    EgUser user = userService.getUser(uid, false);
	    // 获取当前登录用户在该任务中的权限
	    EgRole role = okrService.roleintask(task, user);
	    // 8、如果用户拥有审核权限，可直接拖拽排序
	    if((role.getPurview() & EgPurview.OBJECT_CHECK) == EgPurview.OBJECT_CHECK) {
	        if(krService.sort(krid, sort) == null) return new ResponseResult<>(ResponseMessage.DELETE_FAIL);
	        return new ResponseResult<>(ResponseMessage.OK, krid);
	    }
		// 9、如果用户拥有任务管理的权限，可以排序
	    if((role.getPurview() & EgPurview.OKR_TASK_MG) == EgPurview.OKR_TASK_MG) {
	        if(krService.sort(krid, sort) == null) return new ResponseResult<>(ResponseMessage.UPDATE_FAIL.getStatus(), "排序失败！");
	        return new ResponseResult<>(ResponseMessage.OK, krid);
	    }
	    return new ResponseResult<>(ResponseMessage.INADEQUATE_PERMISSIONS);
    }
}
